package net.butfly.bus.policy;

import net.butfly.albacore.exception.SystemException;
import net.butfly.bus.Constants;
import net.butfly.bus.config.Config;

public class SimpleRouter extends RouterBase implements Router {
	public SimpleRouter(Config config) {
		super(config);
	}

	@Override
	public String route(String tx) {
		String[] nodeIDs = this.lookup(tx);
		if (nodeIDs != null)
			return this.lookup(tx, nodeIDs);
		return null;
	}

	@Override
	public String[] lookup(String code) {
		String[] nodeIds = this.config.matchNodeId(code);
		if (nodeIds != null)
			return nodeIds;
		throw new SystemException(Constants.UserError.TX_NOT_FOUND, "TX [" + code + "] not found.");
	}

	@Override
	public String lookup(String txCode, String[] nodeIDs) {
		return nodeIDs[(int) (Math.random() * nodeIDs.length)];
	}
}
